package com.kayo.specimen.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kayo.specimen.annotion.JsonParam;
import com.kayo.specimen.annotion.PagingParam;
import com.kayo.specimen.model.JsonResult;
import com.kayo.specimen.model.Role;
import com.kayo.specimen.service.RoleService;
import com.kayo.specimen.utility.PagingInfo;
import com.kayo.specimen.utility.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.constraints.NotEmpty;
import java.util.List;

@RequiresPermissions("读取角色")
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @RequestMapping("/index")
    public ModelAndView index(){
        return new ModelAndView("/views/role/list");
    }

    @RequestMapping("/list")
    public Object list(String id,String name, @PagingParam PagingInfo pagingInfo){
        PageHelper.startPage(pagingInfo.getPage(),pagingInfo.getLimit());

        List<Role> roles = roleService.getRoles(id, name, pagingInfo.getOrderByClause());
        PageInfo<Role> pageInfo=new PageInfo<>(roles);
        return JsonResult.success(pageInfo);
    }

    @RequiresPermissions("更新角色")
    @RequestMapping("/add")
    public ModelAndView add(){
        ModelAndView modelAndView = new ModelAndView("/views/role/edit");
        Role role=new Role();
        modelAndView.addObject("role",role);
        return modelAndView;
    }

    @RequiresPermissions("更新角色")
    @RequestMapping("/edit")
    public ModelAndView edit(String id){
        ModelAndView modelAndView = new ModelAndView("/views/role/edit");
        List<Role> roles = roleService.getRoles(id, null,null);
        modelAndView.addObject("role",roles.get(0));
        return modelAndView;
    }

    @RequiresPermissions("更新角色")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Object update(@JsonParam Role role){
        if(StringUtils.isNullOrEmpty(role.getId())){
            roleService.addRoles(role);
        }
        else{
            roleService.updateRoles(role);
        }
        return JsonResult.success(role);
    }

    @RequiresPermissions("删除角色")
    @RequestMapping("/delete")
    public Object delete(@NotEmpty(message = "id不能为空") @JsonParam String[] id){
        roleService.removeRoles(id);
        return JsonResult.success();
    }
}
